package close.kenny.lib.kwindows.taskbar.taskbutton
{
	import close.kenny.lib.kwindows.taskbar.events.KTaskButtonEvent;
	import close.kenny.lib.kwindows.taskbar.taskbutton.skin.TaskButtonSkin;
	import close.kenny.lib.kwindows.window.KWindow;
	
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.events.Event;
	import flash.events.MouseEvent;
	
	import mx.controls.Image;
	import mx.events.CloseEvent;
	import mx.graphics.BitmapFill;
	
	import spark.components.Button;
	import spark.components.PopUpAnchor;
	import spark.components.ToggleButton;

	[Event(name="close", type="com.kenny.lib.taskbar.events.KTaskButtonEvent")]
	public class KTaskButton extends ToggleButton
	{
		/**
		 * 构造函数，设定此按钮的皮肤文件。
		 */
		[SkinPart(required="false")]
		public var closeButton:Button;
		
		[SkinPart(required="false")]
		public var previewImage:BitmapFill;
		
		[SkinPart(required="false")]
		public var popupAnchor:PopUpAnchor;
		
		[Bindable]
		public var window:KWindow;
		public function KTaskButton(window:KWindow)
		{
			super();
			this.window = window;
			setStyle("skinClass", TaskButtonSkin);
			selected=true;
			mouseChildren=true;
		}
		
		private function closeButtonHandle(event:MouseEvent):void
		{
			dispatchEvent(new KTaskButtonEvent(KTaskButtonEvent.CLOSE));
		}
		protected function taskbarButton_mouseOverHandler(event:MouseEvent):void
		{
			if (popupAnchor)
				popupAnchor.displayPopUp = true;
			
			if (previewImage)
			{
				var bitmapData:BitmapData = new BitmapData(this.window.width, this.window.height);
				bitmapData.draw(this.window);
				if (bitmapData)
					previewImage.source = new Bitmap(bitmapData);
			}
		}
		protected function taskbarButton_mouseOutHandler(event:MouseEvent):void
		{
			if (popupAnchor)
				popupAnchor.displayPopUp = false;
		}
		override protected function partAdded(partName:String, instance:Object):void
		{
			super.partAdded(partName, instance);
			addEventListener(MouseEvent.MOUSE_OVER, taskbarButton_mouseOverHandler);
			addEventListener(MouseEvent.MOUSE_OUT, taskbarButton_mouseOutHandler);
			if (instance == closeButton)
			{
				closeButton.addEventListener(MouseEvent.CLICK,closeButtonHandle);
			}
		}
		override protected function partRemoved(partName:String, instance:Object):void
		{
			super.partRemoved(partName, instance);
			removeEventListener(MouseEvent.MOUSE_OVER, taskbarButton_mouseOverHandler);
			removeEventListener(MouseEvent.MOUSE_OUT, taskbarButton_mouseOutHandler);
			if (instance == closeButton)
			{
				closeButton.removeEventListener(MouseEvent.CLICK,closeButtonHandle);
			}
		}
	}
}